<?php

namespace App\controller;

use support\Redis;
use support\Request;
use think\facade\Db;
use Illuminate\Support\Env;
use app\controller\RestBase;
use PhpAmqpLib\Wire\AMQPTable;
use App\validate\OrderValidate;
use PhpAmqpLib\Message\AMQPMessage;
use crmeb\exceptions\AdminException;
use think\exception\ValidateException;
use App\service\order\StoreOrderServices;
use App\service\order\RefundOrderServices;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};


class OrderApi
{
    /**
     * 藏品下单
     * @param Request $request
     * @return \support\Response
     * @throws \Exception
     */
    public function create(Request $request)
    {
        $token = $request->header('XX-Token');
        $deviceType = $request->header('XX-Device-Type');

        $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac', 'wxapp', 'ios'];

        if (empty($token)) {
            return json(['code' => 0, 'msg' => '请传入XX-Token']);
        }

        if (empty($deviceType)) {
            return json(['code' => 0, 'msg' => '请传入XX-Device-Type']);
        }

        if (!in_array($deviceType, $allowedDeviceTypes)) {
            return json(['code' => 0, 'msg' => '设备类型错误']);
        }

        $user = Db::name('user_token')
            ->where('token', $token)
            ->where('device_type', $deviceType)
            ->find();

        if (!$user) {
            return json(['code' => 0, 'msg' => '请先登录', 'user' => $user]);
        }

        $userId = $user['user_id'];

//        $userId = $this->getUserId();
////        var_dump($userId);
//        if (is_array($userId)) {
//            return json($userId);
//        }

        $data = [
            'uid' => $userId,
            'goods_id' => $request->post('goods_id') ?? '', // 藏品id
            'pay_type' => $request->post('pay_type') ?? '', // 支付方式 sd_h5_checkstand 杉德H5收银台支付  hf 汇付支付
            'buy_count' => $request->post('buy_count') ?? 1, // 购买数量
            'order_pk_id' => $request->post('order_pk_id') ?? 0, // 订单主键id 重新付款的时候 传入
        ];

        $validate = new OrderValidate;

        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $storeOrderServices = new StoreOrderServices();

        $expire = 10; // 有效期 10秒
        $key = $userId . ':lock'; // key
        $value = time() + $expire; // 锁的值 = unix 时间戳 + 锁的有效期

        $lock = Redis::setNx($key, $value); // 只能是一个线程 会 变为 true

        if (empty($lock)) {
            return json(['code' => 0, 'msg' => '正在执行中......']);
        } else {
            try {
                $res = $storeOrderServices->orderCreate($userId, (int)$data['goods_id'], (int)$data['buy_count'], $data['pay_type'], (int)$data['order_pk_id']);
            } catch (AdminException $e) {
                Redis::del($key);
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
            Redis::del($key);
        }

        return json(['code' => 1, 'msg' => '抢购成功', 'data' => $res]);
    }

    /**
     * 购买藏品
     * 杉德支付成功通知
     * @param Request $request
     * @return string|\support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function payNotify(Request $request)
    {
        $data = $request->post();

        $storeOrderServices = new StoreOrderServices();
        try {
            $storeOrderServices->payNotify($data);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return '{respCode=000000}';
    }


    /**
     * 藏品下单 压力测试
     * @param Request $request
     * @return \support\Response
     * @throws \Exception
     */
    public function test(Request $request)
    {
        $userId = 314753846876442625;
        $data = [
            'uid' => $userId,
            'goods_id' => $request->get('goods_id') ?? '', // 藏品id
            'pay_type' => $request->get('pay_type') ?? '', // 支付方式 sd_h5_checkstand 杉德H5收银台支付  hf 汇付支付
            'buy_count' => $request->get('buy_count') ?? 1, // 购买数量
            'order_pk_id' => $request->get('order_pk_id') ?? 0, // 订单主键id 重新付款的时候 传入
        ];

        $validate = new OrderValidate;

        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $storeOrderServices = new StoreOrderServices();

        try {
            $res = $storeOrderServices->orderCreateTest($userId, (int)$data['goods_id'], (int)$data['buy_count'], $data['pay_type'], (int)$data['order_pk_id']);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => '测试抢购成功', 'data' => $res]);
    }

    /**
     * 单个查询订单（如果查询支付成功自动 补 推）
     * @param Request $request
     * @return \support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function findQuery(Request $request)
    {
        $data = [
            'orderCode' => $request->get('orderCode') ?? '', // 订单号
        ];

        if (empty($data['orderCode'])) {
            return json(['code' => 0, 'msg' => '请输入查询订单号！']);
        }

        $storeOrderServices = new StoreOrderServices();

        try {
            $res = $storeOrderServices->findQuery($data['orderCode']);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        if (!empty($res) && !empty($res['data'])) {

            $orderInfo = Db::name('store_order')->where('order_id', $data['orderCode'])->find();

            $updateData = [
                'resp_code' => $res['data']['head']['respCode'] ?? '', // 响应码 成功响应码：000000
                'resp_msg' => $res['data']['head']['respMsg'] ?? '', // 响应描述
                'order_msg' => $res['data']['body']['orderMsg'] ?? '', // 订单状态描述
                'order_status' => $res['data']['body']['orderStatus'] ?? '',
                'ori_resp_msg' => $res['data']['body']['oriRespMsg'] ?? '', // 原交易应答描述
                'select_time' => date('Y-m-d H:i:s'),
                'initiative_select_msg' => json_encode($res, JSON_UNESCAPED_UNICODE) // 前端主动查返回的结果
            ];

            $order_status = '';

            if (!empty($updateData['resp_code'])) {
                if ($res['data']['head']['respCode'] == '000000') {

                    $updateData['pay_order_code'] = $res['data']['body']['payOrderCode'] ?? ''; // 渠道订单号 如 ：20220622001317100000000000023895
                    //$updateData['order_status'] = $res['data']['body']['orderStatus'] ?? ''; // 通过杉德订单查询到的状态 00 成功 01 处理中 02 失败 03 已撤销 04 已退货 05 退款处理中

                    $order_status = $updateData['order_status'];

                    if (!empty($res['data']['body']['orderStatus'])) {
                        // 01 处理中
//                        if ($res['data']['body']['orderStatus'] == '01') {
//                            $updateData['status'] = 5; // 订单状态（0 支付中 1 已付款未到账   2 已付款已到账 3 已退款 4 订单超时 5 支付失败（或者待支付））
//                        }
                        if ($res['data']['body']['orderStatus'] != '00') {
                            $updateData['status'] = 5;
                        }
                    }
                } else {
                    if ($orderInfo['status'] == 0) {
                        $updateData['status'] = 5;
                    }
                }
            }

            Db::name('store_order')->where('order_id', $data['orderCode'])->update($updateData);

            if ($order_status == '00') {
                // 说明  根据查询 发现 订单已经支付成功了
                $order_pk_id = $orderInfo['id'];

//                /** @var BoxOrderServices $boxOrderServices */
//                $boxOrderServices = app()->make(BoxOrderServices::class);

                switch ($orderInfo['type']) {
                    // 0 购买藏品
                    case 0:
                        $storeOrderServices->selectPayNotify((int)$order_pk_id);
                        break;
//                    // 1 购买盲盒
//                    case 1:
//                        $boxOrderServices->selectBoxPayNotify((int)$order_pk_id);
//                        break;
//                    // 2 钱包充值
//                    case 2:
//                        $this->services->selectBalanceNotify((int)$order_pk_id);
//                        break;
                }
            }

            return json([
                'code' => 1,
                'msg' => "单个订单查询成功（如果查询支付成功自动补推）!",
                'data' => [
                    'respCode' => $res['data']['head']['respCode'] ?? '', // 响应码 成功响应码：000000
                    'respTime' => $res['data']['head']['respTime'] ?? '', // 响应时间
                    'respMsg' => $res['data']['head']['respMsg'] ?? '', // 响应描述
                    'order_status' => $res['data']['body']['orderStatus'] ?? '', // 通过杉德订单查询到的状态 00 成功 01 处理中 02 失败 03 已撤销 04 已退货 05 退款处理中
                    'pay_order_code' => $res['data']['body']['payOrderCode'] ?? '', // 渠道订单号 如 ：20220622001317100000000000023895
                    'res' => $res
                ]
            ]);

        } else {
            return json(['code' => 0, 'msg' => '未查询到订单数据！']);
        }
    }


    /**
     * 订单退款
     * @param Request $request
     * @return \support\Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderRefund(Request $request)
    {
        $data = [
            'oriOrderCode' => $request->post('oriOrderCode') ?? '', // 要退款的订单号
        ];

        if (empty($data['oriOrderCode'])) {
            return json(['code' => 0, 'msg' => '请输入要退款的订单号！']);
        }

        $refundOrderServices = new RefundOrderServices();

        try {
            $res = $refundOrderServices->orderRefund($data['oriOrderCode']);
        } catch (AdminException $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }

        return json(['code' => 1, 'msg' => "提交退款成功!", $res]);
    }

    /**
     * @return \support\Response
     */
    public function targetHome()
    {
        return redirect(env('PAY_TARGET_URL'));
    }
}
